#include "recbox.h"
#include "ui_recbox.h"
#include<recboxitem.h>
#include<QJsonObject>
#include<QDebug>
#include<math.h>
RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(2==row)
    {
        this->row=row;
        this->col=8;
    }else
    {
       ui->recListDown->hide();

       qDebug()<<"hide";
    }
     imagelist = data;
     currentIndex=0;
     count=ceil(imagelist.size()/col);

    createRecBoxItem();


}
void RecBox::createRecBoxItem()
{
    QList<recBoxItem*> recuplist=ui->recListUp->findChildren<recBoxItem*>();
    for(auto e:recuplist)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }

    QList<recBoxItem*> recdownlist=ui->recListDown->findChildren<recBoxItem*>();
    for(auto e:recdownlist)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }

    int index=0;
    for(int i=currentIndex*col;i<col*currentIndex+col;i++)
    {
        recBoxItem* item=new recBoxItem();
       QJsonObject obj=imagelist[i].toObject();
       item->setText(obj.value("text").toString());
       item->setImage(obj.value("path").toString());
        if(index>=col/2&&row==2)
        {

            ui->recListDownHLayout->addWidget(item);

        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }
        ++index;
    }

}

void RecBox::on_btUp_clicked()
{

    currentIndex--;
    if(currentIndex<0)
    {
        currentIndex=0;
    }
    createRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    currentIndex++;
    if(currentIndex>=count)
    {
        currentIndex=0;
    }
    createRecBoxItem();

}
